package cn.ywang.spring.orm.demo.dao;

import cn.ywang.spring.orm.datasource.DynamicDataSource;
import cn.ywang.spring.orm.demo.model.User;
import cn.ywang.spring.orm.framework.BaseDaoSupport;
import cn.ywang.spring.orm.framework.QueryRule;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

/**
 * @author BeatificWang
 * @date 2019/5/5 23:12
 */
public class UserDao extends BaseDaoSupport<User, Integer> {

	private DynamicDataSource dataSource;

	@Override
	protected String getPKColumn() {
		return "id";
	}

	@Override
	@Resource(name = "dynamicDataSource")
	protected void setDataSource(DataSource dataSource) {
		this.dataSource = (DynamicDataSource) dataSource;
		this.setDataSourceReadOnly(dataSource);
		this.setDataSourceWrite(dataSource);
	}

	/**
	 * @param name
	 * @return
	 */
	public List<User> selectByName(String name) throws Exception {
		//构建一个QueryRule 查询规则
		QueryRule queryRule = QueryRule.getInstance();
		//查询一个name= 赋值 结果，List
		queryRule.andEqual("name", name);
		//相当于自己再拼SQL语句
		return super.select(queryRule);
	}


	public List<User> selectAll() throws Exception {
		QueryRule queryRule = QueryRule.getInstance();
		return super.select(queryRule);
	}

	@Override
	public boolean insert(User user) throws Exception {
		if (user.getAge() >= 18) {
			this.dataSource.getDataSourceEntry().set("db_two");
		}
		else {
			this.dataSource.getDataSourceEntry().set("db_one");
		}
		Integer id = super.insertAndReturnId(user);
		user.setId(id);
		return id > 0;
	}

	@Override
	public boolean update(User user) throws Exception {
		return super.update(user);
	}

	@Override
	public boolean delete(User user) throws Exception {
		return super.delete(user);
	}
}
